import './index.scss'
import { Card, Form, Input, Button, message } from 'antd'
import logo from '@/assets/logo.png'
import { useDispatch,} from 'react-redux';
import { setTokenAsync } from '@/store/modules/user'
import { useNavigate } from 'react-router-dom';
import { useEffect } from 'react';

const Login = () => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const [form] = Form.useForm();
    // 登录成功回调函数
    const onFinish = async (values) => { 
        await dispatch(setTokenAsync({mobile: values.username, code: values.password}))
        // console.log('Success:', values);
        navigate('/')
        message.success({
          content: '登录成功!',
          duration: 1,
        })
    };
    // 登录失败回调函数
    const onFinishFailed = (errorInfo) => { console.log('Failed:', errorInfo.values); };

    // 设置表单的初始值
    useEffect(() => {
      form.setFieldsValue({
        username: '13800000002',
        password: '246810',
      });
    }, [form]);

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
            form={form}
            validateTrigger="onBlur"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
        >
          <Form.Item
            name="username"
            rules={[
                {
                  required: true,
                  message: '请输入手机号码!',
                },
                {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入正确的手机号码!',
                },
              ]}
          >
            <Input size="large" placeholder="请输入手机号"/>
          </Form.Item>
          <Form.Item
            name="password"
            rules={[
                {
                  required: true,
                  message: '请输入密码!',
                }
            ]}
          >
            <Input size="large" placeholder="请输入密码"/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login